<script setup>
    import userApi from "@/api/user.js";
    import {Plus} from "@element-plus/icons-vue";

    import {ElMessage} from 'element-plus'
    import {useRouter} from 'vue-router'
    const router = useRouter();

    import {useTokenStore} from "@/store/token.js";
    const tokenStore = useTokenStore();
    import {useUserInfoStore} from "@/store/userInfo.js";
    import {ref} from "vue";

    const userInfoStore = useUserInfoStore();

    const titleName = "更换头像"

    const getUserInfo = () => {
        userApi.userInfo().then(result => {
            if (result.code === 0) {
                userInfoStore.setUserInfo(result.data)
            }
        })
    }
    getUserInfo()

    //修改头像
    const user = ref({})
    Object.assign(user.value, userInfoStore.user)
    const headers = ref({
        //添加token
        Authorization: tokenStore.token
    })

    const handleAvatarSuccess = (result) => {
        user.value.image = result.data
    }

    const updateAvatar = () => {
        userApi.update(user.value).then(result => {
            if (result.code === 0) {
                ElMessage({message: result.msg, type: 'success',})
                //重新加载最新数据
                getUserInfo()
                //跳转到主界面
                router.push('/')
            } else {
                ElMessage.error(result.msg)
            }
        })
    }
</script>

<template>
    <el-card class="">
        <template #header>
            <div class="header">
                <strong>{{titleName}}</strong>
            </div>
        </template>

        <el-form :model="user">
            <el-form-item label="头像" :label-width="60">
                <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :headers="headers"
                >
                    <img v-if="user.image" :src="user.image" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="updateAvatar">
                    确认
                </el-button>
            </div>
        </template>
    </el-card>
</template>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>